package com.css.resoft.p2pmonitor.service;

import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.alibaba.fastjson.JSONObject;
import com.css.resoft.p2pmonitor.entity.MonthReport;
import com.css.resoft.p2pmonitor.util.P2PFileUtil;
import com.css.resoft.p2pmonitor.util.ReadConifgUtil;
import com.css.resoft.p2pmonitor.util.SAXParserHandle;
import com.css.resoft.p2pmonitor.vo.SchedulerRunningInfoVO;
import com.css.sword.core.components.scheduler.api.SwordSchedulerUtils;
import com.css.sword.core.components.scheduler.job.info.ISwordJobDefInfo;
import com.css.sword.core.components.scheduler.trigger.ISwordJobTrigger;
import com.css.sword.core.kernel.base.annotation.Service;
import com.css.sword.core.kernel.base.annotation.ServiceContainer;
import com.css.sword.core.kernel.base.persistence.IPersistenceService;
import com.css.sword.core.kernel.utils.SwordPersistenceUtils;
import com.css.sword.web.request.ISwordRequest;
import com.css.sword.web.response.ISwordResponse;
import com.css.sword.web.response.SwordResponseFactory;


@ServiceContainer(value="P2PData")
public class P2PData {
	
	public static String host = ReadConifgUtil.getInstance().getHost();
	public static int port = ReadConifgUtil.getInstance().getPort();
	
	@Service(value = "putData")
	public ISwordResponse putData(ISwordRequest iReq) throws Exception{
		
		ISwordResponse dRes = SwordResponseFactory.createSwordResponseInstance(iReq);
		String fileDir = iReq.getData("fileDir");// "D:"+File.separator+"p2p";
		String errFileDir = iReq.getData("errFileDir"); // "D:"+File.separator+"err"+File.separator;
		String cleanFileDir = iReq.getData("cleanFileDir"); // "D:"+File.separator+"clean";
		
		JSONObject result = new JSONObject();
		
		if(fileDir.trim().isEmpty() || cleanFileDir.trim().isEmpty()){
			result.put("result", "false");
			result.put("message", "unvalid param");
			dRes.setModel(result);
			return dRes;
		}
		
		try {
			
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			SAXParserHandle handle = new SAXParserHandle(host,port);
			List<String> filePaths = new ArrayList<String>();
			
			int num = 0;
			P2PFileUtil.getFileList(fileDir,filePaths);
			
			handle.openThrift();
			
			for(String file :filePaths){
				System.out.println(file);
				num++;
				System.out.print(num);
				P2PFileUtil.parseZipFile(parser,handle,file,errFileDir);
				if(!errFileDir.trim().isEmpty())
					P2PFileUtil.moveZipFile(file,cleanFileDir);
			}
			handle.closeThrift();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.put("result", true);
		result.put("message", "ok");
		dRes.setModel(result);
		return dRes;
	}

	@Service(value = "setReportScheduler")
	public ISwordResponse setReportScheduler(ISwordRequest iReq) throws Exception{
		ISwordResponse dRes = SwordResponseFactory.createSwordResponseInstance(iReq);
		JSONObject  triggerParams = iReq.getJsonData().getJSONObject("triggerParams");
		if(triggerParams == null)
			return null;
		
		String second = triggerParams.getString("second");
		String minute = triggerParams.getString("minute");
		String hour = triggerParams.getString("hour");
		String day = triggerParams.getString("day");
		String month = triggerParams.getString("month");
		String week = triggerParams.getString("week");
		String year = triggerParams.getString("year");
		
		boolean isAutoResume = true;
    	ISwordJobTrigger jobTrigger = SwordSchedulerUtils.createSwordJobTriggerWithCronValue(second, minute, hour, day, month, week, year, isAutoResume);
    	
    		String jobName = "ComputeReportJob";
    		
    		ISwordJobDefInfo jobInfo = SwordSchedulerUtils.findJob(jobName,"ComputeReportGroup");
    		if(jobInfo == null){
    			jobInfo = SwordSchedulerUtils.createSwordJobInfoWithServiceName("/Report/computeReport");
    			jobInfo.setJobGroup("ComputeReportGroup");
    			jobInfo.setJobName(jobName);
    	    	jobInfo.setDescription("nothing");
    	    	jobInfo.setSingleJob(true);
    	    	jobInfo.setJobTrigger(jobTrigger);
    	    	try {
    	    		SwordSchedulerUtils.registerJobInfo(jobInfo);
    	    	} catch (Exception e) {
    				e.printStackTrace();
    				dRes.setModel(false);
    			}
    		}else{
    			jobInfo.setJobTrigger(jobTrigger);
    			SwordSchedulerUtils.upgradeJobInfo(jobInfo);
    		}
    		dRes.setModel(true);
		
    	return dRes;
	}

	@Service(value="getSchedulerInfo")
	public ISwordResponse getSchedulerInfo(ISwordRequest iReq){
		ISwordResponse dRes = SwordResponseFactory.createSwordResponseInstance(iReq);
		
		String jobName = "ComputeReportJob";
		
		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService();
		SchedulerRunningInfoVO result = null;
		try {
			String sql = "SELECT s.job_status,i.first_execute_time,i.last_execute_time,i.finished_time,i.execute_counts,i.completed_success_counts "
					+ " FROM sword_scheduler s LEFT JOIN  sword_scheduler_running_info i "
					+ "ON s.job_id = i.job_id "
					+ "WHERE s.job_name = ? "
					+ "AND s.create_time = (SELECT MAX(create_time) FROM sword_scheduler WHERE job_name = ? ) ";
			Object []params = {jobName,jobName};
			result = dao.findOneBySql(SchedulerRunningInfoVO.class, sql, params);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		dRes.setModel(result);
		return dRes;
	}
	
	@Service(value="pauseSchedulerJob")
	public ISwordResponse pauseSchedulerJob(ISwordRequest iReq){
		ISwordResponse dRes = SwordResponseFactory.createSwordResponseInstance(iReq);
		try {
			SwordSchedulerUtils.pauseJob("ComputeReportJob","ComputeReportGroup");
			dRes.setModel(true);
		} catch (Exception e) {
			e.printStackTrace();
			dRes.setModel(false);
		}
		return dRes;
	}
	
	
	@Service(value = "saveReport")
	public void saveReport(List<MonthReport> monthReports) throws Exception{
		
		IPersistenceService dao = SwordPersistenceUtils.getPersistenceService("datacore");
		for (MonthReport monthReport : monthReports) {
			try {
				dao.saveOrUpdate(monthReport);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}			
	}
}
